/*
 * Copyright 2015 The gRPC Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.todu.leaning.opentelemetry_loki.grpc.helloworld;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.grpc.stub.StreamObserver;
import io.opentelemetry.api.trace.Span;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/** Server that manages startup/shutdown of a {@code Greeter} server. */
@Component
@Slf4j
public class HelloWorldServer {

  @Autowired private GreeterImpl greeterImpl;
  public static final int PORT = 50052;
  private Server server;

  @PostConstruct
  public void start() throws IOException {
    server = ServerBuilder.forPort(PORT).addService(greeterImpl).build().start();
    log.info("Server started, listening on " + PORT);
  }

  @PreDestroy
  private void stop() throws InterruptedException {
    if (server != null) {
      server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
    }
  }

  /** Main launches the server from the command line. */
  @Service
  public static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
    private static final AtomicInteger counter = new AtomicInteger();

    @Override
    public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
      int i = counter.incrementAndGet();
      if (i % 2 == 0) {
        responseObserver.onError(Status.INTERNAL.withDescription("服务端异常").asRuntimeException());
        return;
      }

      String msg = "这是grpc服务端回复的消息，当前访问计数：" + i;
      log.info(msg);
      HelloReply reply =
          HelloReply.newBuilder()
              .setMessage(req.getName() + " ， " + LocalDateTime.now() + ", " + msg)
              .build();
      responseObserver.onNext(reply);
      responseObserver.onCompleted();
    }
  }
}
